package com.sheep.opt;

import org.apache.log4j.Logger;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Timer;

/**
 * Created by IntelliJ IDEA.
 * User: wnj
 * Date: 2010-11-15
 * Time: 19:50:05
 * To change this template use File | Settings | File Templates.
 */
public class Initiate implements ServletContextListener {
	Timer priceTimer;
	protected Logger log = Logger.getLogger(this.getClass());
	public void contextInitialized(ServletContextEvent arg0){
		String name = null;
		try {
            // set jmagick property, not using systemclassloader
            System.setProperty("jmagick.systemclassloader","no");
			InetAddress hostIP = InetAddress.getLocalHost();
			name = hostIP.getHostName();
			arg0.getServletContext().setAttribute("hostName", name);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
        log.info("Init Context");
		Resources.init();
		arg0.getServletContext().setAttribute("urlMain", Resources.getString("sys.url.main"));
        arg0.getServletContext().setAttribute("headPrefix", "http://"+Resources.getString("sys.domain.head"));
        arg0.getServletContext().setAttribute("xiaoquPrefix", "http://xiaoqu."+Resources.getString("sys.domain.main")+
                                                            arg0.getServletContext().getContextPath());


//        log.info("start price timer");
//		priceTimer = new Timer();
////		priceTimer.schedule(new PriceTask(), (long)1000 * 60, (long) 60 * 60 * 1000);
//        priceTimer.schedule(new PriceTask(), (long)1000 * 60, (long) 60 * 60 * 1000);
//		log.info("start price timer end");
	}

	public void contextDestroyed(ServletContextEvent arg0) {
		arg0.getServletContext().removeAttribute("urlMain");
		arg0.getServletContext().removeAttribute("urlStatic");
        arg0.getServletContext().removeAttribute("basePath");
        arg0.getServletContext().removeAttribute("urlPrefix");
        arg0.getServletContext().removeAttribute("headPrefix");
        if (priceTimer != null) {
            try {
                priceTimer.cancel();
                log.info("price timer canceled");
            }
            catch (Exception e) {
                log.error(" cancle price timer exception " + e);
            }
            priceTimer = null;
        }
        log.info("Destroy context");
	}
}

